package org.jeecg.modules.generator.utils;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.*;
import org.jeecg.common.exception.JeecgBootException;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * Created by Ay on 2016/7/27.
 */
public class FreeMarkerTemplateUtils {

    private FreeMarkerTemplateUtils(){}
    private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);

    static{
        //这里比较重要，用来指定加载模板所在的路径
        CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/templates/generator"));
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
    }

    public static Template getTemplate(String templateName) throws IOException {
        try {
            return CONFIGURATION.getTemplate(templateName);
        } catch (IOException e) {
            throw e;
        }
    }


    /**
     * 根据实体对象解析模板
     * @param templateStr     模板内容
     * @param input        实体对象
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    public static String freemarkerProcess(Map input, String templateStr) {
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String template = "content";
        stringLoader.putTemplate(template, templateStr);
        Configuration cfg = new Configuration();
        cfg.setTemplateLoader(stringLoader);
        StringWriter writer = null;
        try {
            Template templateCon = cfg.getTemplate(template);
            writer = new StringWriter();
            templateCon.process(input, writer, ObjectWrapper.BEANS_WRAPPER);
            return writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new JeecgBootException("freemark模版解析失败！");
        } finally {
            if(writer != null){
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void clearCache() {
        CONFIGURATION.clearTemplateCache();
    }
}
